﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Data.SqlClient;

public partial class resetpassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return;
        if (Request.QueryString.Count < 1 || Request.QueryString["qr"] == null || Request.QueryString["qr"].ToString() == "")
            showMessage("Invalid Request.");
        else
        {
            if (!checkEmailActivation(Request.QueryString["qr"].ToString()))
            {
                string link = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "forgotpassword.aspx";
                showMessage("Your password reset link has expired. Please click <a href=\"" + link + "\">here</a> to initiate the request again.");
            }
            else if (checkDBconnection())
                loadHintQues();
            else
                showMessage("Unable to process your request now. Please try again later.<br/><br/>Alternatively, let us know about this problem at maxblox_support@cellarstone.com");
        }
    }

    private void loadHintQues()
    {
        try
        {
            HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
            DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where acr_id='5937020e4add150Y'");
            if (dt != null && dt.Rows.Count > 1)
            {
                ddl_hintQuestions.DataSource = dt;
                ddl_hintQuestions.DataTextField = "mem_name";
                ddl_hintQuestions.DataValueField = "mem_id";
                ddl_hintQuestions.DataBind();
            } 
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("resetpassword: loadHintQues: Error: " + ex.Message);
        }
    }
    private bool checkEmailActivation(string sForgotPwdID)
    {
        bool sRet = false;
        HDDatabase hdd = null;
        try
        {
            if (Session["servercon"] == null)
                hdd = new HDDatabase();
            else
                hdd = new HDDatabase(Session["servercon"].ToString());
            DataRow dr = hdd.GetTableRow("select [company_id], [user_id], [active] from [sy_forgot_password_log] where [af_row_id] = '" + sForgotPwdID + "';");
            if (dr == null) return sRet;
            if (dr["active"].ToString().ToLower() != "true") return sRet;
            hf_company_rowkey.Value = dr["company_id"].ToString();
            hf_user_rowkey.Value = dr["user_id"].ToString();
            sRet = true;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("resetpassword: checkDBconnection: Error: " + ex.Message);
        }
        return sRet;
    }
    private bool checkDBconnection()
    {
        bool sRet = false;
        HDDatabase hdd = null;
        try
        {
            if (Session["servercon"] == null)
                hdd = new HDDatabase();
            else
                hdd = new HDDatabase(Session["servercon"].ToString());
            string strCompanyId = hdd.GetColumnValue("select [company_id] from [ngcompany] where [af_row_id] = '" + hf_company_rowkey.Value + "';");
            hf_company_id.Value = strCompanyId;
            if (string.IsNullOrEmpty(strCompanyId)) return sRet;
            DataTable dt = hdd.GetDataTable("select * from ngcompanyserver where company_id='" + strCompanyId.Replace("'", "''") + "'");
            if (dt.Rows.Count < 1) dt = hdd.GetDataTable("select * from ngcompanyserver where company_id = (select [af_row_id] from [ngcompany] where [company_id] = '" + strCompanyId.Replace("'", "''") + "')");
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + strCompanyId + @""";Password=""" + strCompanyId + @"_123"";Initial Catalog="""
                            + row["dbname"].ToString() + @"""";
                HDDatabase hdtemp = new HDDatabase(strConn);
                if (hdtemp.isValidConnection())
                {
                    sRet = true;
                    Session["dbcon"] = strConn;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("resetpassword: checkDBconnection: Error: " + ex.Message);
        }
        return sRet;
    }
    protected void bt_continue_click(object sender, EventArgs e)
    {
        try
        {
            //check whether valid user
            bool updateDone = false;
            HDDatabase hdd = new HDDatabase(Session["servercon"].ToString());
            DataRow dr_usr = hdd.GetTableRow("select * from [ngcompanyuser] where [af_row_id] = '" + hf_user_rowkey.Value + "' and [company_id] = '" + hf_company_id.Value + "'");
            if (dr_usr == null)
            {
                showMessage("Unable to process your request now. Please try again later.");
                return;
            }
            if (dr_usr["hint_question"].ToString().Trim() == "" || dr_usr["hint_answer"].ToString().Trim() == "")
            {
                showMessage("Hint Question and Answer not specified for this user. Please contact your administrator.");
                return;
            }
            if (dr_usr["hint_question"].ToString().ToLower() != ddl_hintQuestions.SelectedValue.ToLower() || dr_usr["hint_answer"].ToString().ToLower() != txt_hintAns.Text.ToLower())
            {
                lbl_Hint_err.Text = "Hint question and answer does not match. Please retry.";
                return;
            }

            string newPassword = getNewPassword();
            string newPasswordEnc = security.encrypt(newPassword);

            HDDatabase hdUser = new HDDatabase(Session["dbcon"].ToString());
            dr_usr = hdUser.GetTableRow("select * from sy_usr where af_row_id = '" + hf_user_rowkey.Value + "'");
            hf_user_id.Value = dr_usr["user_id"].ToString();
            LogWriter.WriteLog("Reset Password - Done by user:" + hf_user_id.Value);
            string sFromMailID = hdUser.GetColumnValue("select mem_value2 from sy_acr_mem where af_row_id='b13034b44961ff77';");

            if (hdd.ExecuteCmdObj(new SqlCommand("update ngcompanyuser set password='" + newPasswordEnc.Replace("'", "''") + "' where af_row_id ='" + hf_user_rowkey.Value + "' and company_id = '" + hf_company_id.Value + "'")) > 0)
                if (hdUser.ExecuteCmdObj(new SqlCommand("update sy_usr set password='" + newPasswordEnc.Replace("'", "''") + "' where af_row_id ='" + hf_user_rowkey.Value + "'")) > 0)
                    if (hdd.ExecuteCmdObj(new SqlCommand("update sy_forgot_password_log set active = 0 where af_row_id ='" + Request.QueryString["qr"].ToString() + "'")) > 0)
                        updateDone = true;
            if (updateDone == false)
            {
                showMessage("Unable to process your request now. Please try again later.<br/><br/>Alternatively, let us know about this problem at " + sFromMailID);
                return;
            }
            else
            {
                AuditLog AL = new AuditLog();
                AL.WritePasswordSecurityLog("e51e0327224a2eb9", hf_user_rowkey.Value, newPasswordEnc, "reset forgotten password");
                AL = null;
            }
            string firstName = dr_usr["first_name"].ToString();
            string sLoginLink=Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "default.aspx";
            string sUserEmailId = getUserEmailID(hf_user_id.Value);

            CommonFunctions objCmnFun = new CommonFunctions();
            if (objCmnFun.ValidateEmailID(sUserEmailId))
            {
                string content = ReadHtmFile();
                content = content.Replace("$user$", firstName);
                content = content.Replace("$userid$", hf_user_id.Value);
                content = content.Replace("$password$", newPassword);
                content = content.Replace("$path$", sLoginLink);
                content = content.Replace("\r\n", "");
                if (SentInEmailQueue(sUserEmailId, sFromMailID, true, content.Replace("'", "''"), "MaxBlox - New Password"))
                    showMessage("An email with the new password has been sent to '" + sUserEmailId + "' . Please check your email.");
                else
                    showMessage("Unable to process your request now. Please try later.");
            }
            else
                showMessage("Your password is reset and is enclosed below.<br /><br />User ID: " + hf_user_id.Value + "<br />Password: " + newPassword + "<br /><br />Please change your password after logging in. Click&nbsp;<a href=\"" + sLoginLink + "\">here</a>&nbsp;to login in MaxBlox.<br />If you have any questions, contact your administrator.");
        }
        catch (Exception ee)
        {
            LogWriter.WriteLog("Error in forgot password submission. Error: " + ee.Message);
            showMessage("Unable to process your request now. Please try later.");
        }
    }
    private string getNewPassword()
    {
        return RandomString(7, false);
    }
    private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }
    
    public string ReadHtmFile()
    {
        string fileName = Server.MapPath("") + "/ResetPasswordMailContent.htm";
        string content;
        FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        content = reader.ReadToEnd();
        reader.Close();
        return content;
    }
    private string getUserEmailID(string sUserID)
    {
        string sRet = "";
        try
        {
            HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
            DataRow dr = hdd.GetTableRow("select [mem_value2] as table_name, [mem_value3] as field_name from [sy_acr_mem] where [acr_id] = '30e5b719afe1e5be' and [af_row_id] = '76bc31960d22cc50' and [mem_value1] = 'enabled';");
            if (dr == null) return sRet;
            sRet = hdd.GetColumnValue("select " + dr["field_name"].ToString() + " from " + dr["table_name"].ToString() + " where user_id = '" + sUserID + "';");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: getUserEmailID: Error: " + ex.Message);
        }
        return sRet;
    }
    private bool SentInEmailQueue(string sToEmailID, string sFromMailID, bool isHTML, string content, string subject)
    {
        bool sRet = false;
        ScreenReader SR = new ScreenReader();
        SqlConnection SqlCon = null;
        SqlCommand sqlCmd = null;
        try
        {
            string sConn = HttpContext.Current.Session["servercon"].ToString();
            HDDatabase Hdd = new HDDatabase(sConn);

            string strQuery = "INSERT INTO [email_queue] ([to_address],[from_address],[isHTML],[subject],[content],[priority],[delivery],[created_at],[row_id],[bcc_address]) " +
                "VALUES ('" + sToEmailID + "','" + sFromMailID + "'," + (isHTML ? 1 : 0) + ",'" + subject + "','" + content + "',0,'" + DateTime.Now.ToUniversalTime() + "','" + DateTime.Now.ToUniversalTime() + "','" + SR.getHashKey() + "','')";

            SqlCon = new SqlConnection(sConn);
            sqlCmd = new SqlCommand(strQuery, SqlCon);
            int execute = Hdd.ExecuteCmdObj(sqlCmd);
            if (execute > 0) sRet = true;
            Hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SentInEmailQueue :" + ex.Message);
            return false;
        }
        finally
        {
            if (SqlCon != null)
            {
                if (SqlCon.State.Equals(ConnectionState.Open))
                    SqlCon.Close();
                SqlCon.Dispose();
            }
            if (sqlCmd != null)
                sqlCmd.Dispose();
            SR = null;
        }
        return sRet;
    }
    private void showMessage(string sMsg)
    {
        div_hint.Visible = false;
        div_error.Visible = true;
        lbl_validate_info.Text = sMsg;
        lbl_img_req.Visible = false;
        bt_continue.Visible = false;
    }
}